﻿// TestClient.Web.UploadHandler.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.html)
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2010
// ----------------------------------------------------------------------------
// File:       UploadHandler.cs
// Author:     HSS\gbanta
// Created:    07/16/2011
// Modified:   07/16/2011
// ----------------------------------------------------------------------------
using System.Diagnostics;
using System.IO;
using HSS.Interlink.Web;

namespace TestClient.Web
{
	public class UploadHandler : HSS.Interlink.Web.BaseUploadHandler
	{
		/// <summary>
		/// The Folder where the uploaded files are stored.
		/// </summary>
		public static string FileStoreFolder = @"Interlink\Uploads";

		// If you support retries
		//string retryKey;

		public UploadHandler()
		{
			//
			// Uncomment the following line to turn off purging of temp files.
			//
			// NOTE:
			// The default value for purging is 5 minutes.
			// If your uploads take longer than 5 minutes
			// you WILL have to modify this to be longer
			// than your anticipated longest individual
			// file upload duration.
			//
			//this.PurgeInterval = 0;
		}

		string GetFilePath()
		{
			return Path.Combine(this.GetFolder(FileStoreFolder), this.FileName);
		}

		#region BaseUploadHandler Members
		public override bool CheckFileExists()
		{
			//Debug.WriteLine("CheckFileExists...");

			// Take some action based upon the metadata.
			//Debug.WriteLine("Metadata: " + this.Metadata);

			string file = GetFilePath();
			return File.Exists(file); // If you support overwriting files, do so in CreateNewFile.
		}
		public override Responses CreateNewFile()
		{
			#region Test Retry (see AppendToFile)
			// If you support for retries
			//this.retryKey = this.Query.JobId + this.FileName + "retries";
			//this.Context.Cache.Add(retryKey, 0, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
			#endregion

			// Take some action based upon the metadata.
			//Debug.WriteLine("Metadata: " + this.Metadata);

			string file = this.GetFilePath();
			try
			{
				if (File.Exists(file))// If you support overwriting files, do so here.
					File.Delete(file);
			}
			catch { }

			File.Create(file).Close();

			return HSS.Interlink.Web.Responses.Success;
		}
		public override Responses AppendToFile(byte[] buffer)
		{
			//System.Threading.Thread.Sleep(1200);
			//Debug.WriteLine("Appending...");

			// Take some action based upon the metadata.
			//Debug.WriteLine("Metadata: " + this.Metadata);

			#region Test exception
			//throw new Exception("test");
			#endregion

			#region Test Retry (see CreateNewFile)
			// If you support for retries
			// If not able to persist chunk, request a Retry...
			//if (someTest == Failed)
			//{
			//    int retries = 0;
			//    this.retryKey = this.Query.JobId + this.FileName + "retries";
			//    object objRetries = this.Context.Cache[retryKey];
			//    if (null == objRetries)
			//        retries = 1;
			//    else
			//        retries = (int)objRetries + 1;
			//    this.Context.Cache[retryKey] = retries;
			//    if (retries > 3)
			//        return HSS.Interlink.Web.Responses.FatalError;
			//    return HSS.Interlink.Web.Responses.AppendFileRetry;
			//}
			#endregion

			string file = this.GetFilePath();
			using (FileStream fs = File.Open(file, FileMode.Append))
				fs.Write(buffer, 0, buffer.Length);
			return HSS.Interlink.Web.Responses.Success;
		}
		public override void CancelUpload()
		{
			string file = this.GetFilePath();
			try
			{
				if (File.Exists(file))
					File.Delete(file);
			}
			catch { }
		}
		public override string UploadComplete()
		{
			string file = GetFilePath();

			// Move to final destination.
			//File.Copy(file, finalFile);

			// Delete
			//File.Delete(file);

			//Debug.WriteLine("Completed...");

			return "Hey we made it!"; // Optional string to return to caller.
		}
		public override bool IsAuthorized()
		{
			//Debug.WriteLine("IsAuthorized...");

			#region Test Authorization
			//if (this.Context.User.Identity.IsAuthenticated)
			//{
			//    if (this.Context.User.IsInRole("requiredRole"))
			//        return true;
			//}
			//return false;
			#endregion

			return true;
		}
		public override void OnError(System.Exception ex)
		{
			// LogFile.Write(ex.ToString());

			// Log the error...
			HSS.Logging.Log.WriteException(ex, this.UserName, "UploadHandler", "TestClient");

			string file = this.GetFilePath();
			try
			{
				if (File.Exists(file))
					File.Delete(file);
			}
			catch { }
		}
		#endregion
	}
}